package com.learning.thread.base.sync;

/**
 * ClassName: SynchronizedBothMethod
 * Description: 线程互斥，方法之间也是互斥的。 因为锁的是对象
 * <p>
 * Date: 2018/6/28 17:26 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class SynchronizedBothMethod {

    public static void main(String[] args) {
        SynchronizedBothMethod.test1();
    }

    public static void test1() {
        Data data = new Data();
        new Thread(new Thread0(data), "thead 0 ").start();
        new Thread(new Thread1(data), "thead 1 ").start();
    }

    static class Thread0 implements Runnable {

        private Data data;

        public Thread0(Data data) {
            this.data = data;
        }

        @Override
        public void run() {
            data.get1("abcdefghijklmnopqrztuvwzyz");
        }
    }

    static class Thread1 implements Runnable {

        private Data data;

        public Thread1(Data data) {
            this.data = data;
        }

        @Override
        public void run() {
            data.get2("1234567890123456789");
        }
    }


    /**
     * 线程互斥，锁的是数据类
     * 两个方法也是互斥的
     */
    static class Data {

        /**
         * 锁方法，其实锁得还是对象
         *
         * @param name
         */
        private synchronized void get1(String name) {
            int len = name.length();
            for (int i = 0; i < len; i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }

        /**
         * this就是Data这个对象
         * 锁定同一个对象 get1、 get2是互斥的
         * 所以
         *
         * @param name
         */
        private synchronized void get2(String name) {
            int len = name.length();
            for (int i = 0; i < len; i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }

    }

}
